import React, { useEffect, useState } from 'react';
import { fetchShareParamInfo } from '@/server/shop'
import { fetchWechatAuth } from "@/server/login";
import { wechatAuth } from "@/utils/utils";
import Taro, { useLaunch, getCurrentInstance } from "@tarojs/taro";
import { View } from '@tarojs/components'
import Router from '@/utils/router'
import './index.scss';
const Dedirect = (props) => {
  useEffect(() => {
    reduceInIt()
  }, [])
  const reduceInIt = () => {
    const {
      scene,
      openType
    } = getCurrentInstance().router.params;
    if (scene) {
      fetchShareParamInfo({ paramKey: scene }).then(val => {
        const {
          param
        } = val;
        if (param && JSON.parse(param)) {
          initWechat(JSON.parse(param))
        }
      }).catch(e => {
        initWechat()
      });
    } else if (openType === 'gzh') {
      Taro.setStorageSync("userInfo", {
        ...getCurrentInstance().router.params,
      });
      initWechat(getCurrentInstance().router.params)
    }
    else if (openType === 'wechatShare') {
      initWechat(getCurrentInstance().router.params)
    } else {
      const { organizationId } = Taro.getStorageSync('userInfo') || {}
      if (!organizationId) {
        Router('selectOrganization')
      }

    }
  }
  const initWechat = (params = {}) => {
    const { organizationId, type } = params
    const path = {
      home: 'user',
      personalCenter: 'me',
      microPage: 'microPage',
      shopDetail: 'shopDetail'
    }[type]
    wechatAuth((e) => {
      fetchWechatAuth({ code: e, organizationId: organizationId }).then((val) => {
        const { userInfo } = val;
        Taro.setStorageSync("userInfo", {
          ...userInfo,
          ...params,

        });
        if (Object.keys(params).length === 0) {
          Router('user', {
            args: {
              ...params
            },
            linkType: 'reLaunch'
          })
        }
        else {
          Router(path ? path : 'shopDetail', {
            args: {
              ...params
            },
            linkType: 'reLaunch'
          })
        }
      }).catch(error => {
        if (Object.keys(params).length === 0) {
          Router('user', {
            args: {
              ...params
            },
            linkType: 'reLaunch'
          })
        }
        else {
          Router(path ? path : '/live/shopDetail', {
            args: {
              ...params
            },
            linkType: 'reLaunch'
          })
        }
      });
    });
  }
  return <View></View>;
};
export default Dedirect